package com.mystudy.jcu.cyclicBarrier;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * TODO: 使用{@link CountDownLatch}实现类似的{@link java.util.concurrent.CyclicBarrier}的回调功能
 * 区别：
 * 1.CountDownLatch不能reset，而CyclicBarrier可以
 * 2.CountDownLatch工作线程互不关心，CyclicBarrier必须等到同一个共同的点，才能执行某个动作
 * 共同点：
 *
 * @author acy
 * @since 2019/06/18 17:22
 */
public class CyclicBarrierTest2 {
	static class MyCountDownLatch extends CountDownLatch{
		private final Runnable runnable;

		public MyCountDownLatch(int count, Runnable runnable) {
			super(count);
			this.runnable = runnable;
		}
		public void countDown(){
			super.countDown();
			if (getCount()==0){
				this.runnable.run();
			}
		}
	}

	public static void main(String[] args) {
		MyCountDownLatch latch = new MyCountDownLatch(2, () -> {
			System.out.println("all job down");
		});
		new Thread(()->{
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			latch.countDown();
			System.out.println(Thread.currentThread().getName()+"finish work");
		}).start();
		new Thread(()->{
			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			latch.countDown();
			System.out.println(Thread.currentThread().getName()+"finish work");
		}).start();
	}
}
